import 'dart:async';
import 'package:stacked/stacked.dart';
import 'package:vista/shared/models/user_frame.dart';
import 'package:vista/shared/services/auth_focus.dart';
import 'package:vista/shared/services/dialog_lens.dart';

/// 视频通话视图模型
/// 管理视频通话页面的数据和状态
class VideoCallViewModel extends BaseViewModel {
  final AuthFocus _authFocus;
  final DialogLens _dialogLens;
  final String otherUserId;

  VideoCallViewModel(this._authFocus, this._dialogLens, this.otherUserId);

  UserFrame? _currentUser;
  UserFrame? get currentUser => _currentUser;

  UserFrame? _otherUser;
  UserFrame? get otherUser => _otherUser;

  Timer? _autoHangupTimer;
  Timer? _dotAnimationTimer;
  bool _isManualHangup = false;
  bool get isManualHangup => _isManualHangup;
  void Function()? onAutoHangup;

  int _dotCount = 1;
  int get dotCount => _dotCount;

  /// 初始化数据
  Future<void> initialize() async {
    setBusy(true);
    try {
      _currentUser = await _authFocus.getCurrentUser();
      if (_currentUser == null) {
        setBusy(false);
        return;
      }

      final allUsers = await _authFocus.getUsers();
      _otherUser = allUsers.firstWhere(
        (u) => u.id == otherUserId,
        orElse: () => allUsers.first,
      );

      // 启动12秒自动挂断定时器
      _startAutoHangupTimer();
      // 启动点动画定时器
      _startDotAnimationTimer();
    } finally {
      setBusy(false);
    }
  }

  /// 启动自动挂断定时器
  void _startAutoHangupTimer() {
    _autoHangupTimer = Timer(const Duration(seconds: 12), () {
      if (!_isManualHangup) {
        _handleAutoHangup();
        onAutoHangup?.call();
      }
    });
  }

  /// 启动点动画定时器
  void _startDotAnimationTimer() {
    _dotAnimationTimer = Timer.periodic(const Duration(milliseconds: 500), (
      timer,
    ) {
      _dotCount = (_dotCount % 3) + 1;
      notifyListeners();
    });
  }

  /// 处理自动挂断（对方未响应）
  Future<void> _handleAutoHangup() async {
    if (_currentUser == null) return;

    // 发送拨打失败消息
    await _dialogLens.sendCallFailedMessage(
      senderId: _currentUser!.id,
      receiverId: otherUserId,
    );

    notifyListeners();
  }

  /// 手动挂断（用户取消通话）
  Future<void> hangup() async {
    _isManualHangup = true;
    _autoHangupTimer?.cancel();
    _dotAnimationTimer?.cancel();
    notifyListeners();
  }

  @override
  void dispose() {
    _autoHangupTimer?.cancel();
    _dotAnimationTimer?.cancel();
    super.dispose();
  }
}
